package com.lagou.client;

import com.lagou.service.JSONSerializer;
import com.lagou.service.RpcEncoder;
import com.lagou.service.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class RpcConsumer {

    //创建线程池对象
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static UserClientHandler userClientHandler;

    private static Bootstrap bootstrap;
    private static ChannelFuture channelFuture;
    private static EventLoopGroup group;

    private static final int MAX_RETRY = 5;
    private static Channel channel;
    private static Boolean ifConnecting = false;
    private static Boolean ifNeedReconnect = false;
    private static String host;
    private static int thisPort;


    //1.创建一个代理对象 providerName：UserService#sayHello are you ok?
    public Object createProxy(final Class<?> serviceClass,String ip,int port){
        //借助JDK动态代理生成代理对象
        return  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {


            public Object invoke(Object proxy, Method method, Object[] args) throws InterruptedException, ExecutionException {
                //（1）调用初始化netty客户端的方法

                if(userClientHandler == null||ifNeedReconnect||!host.equals(ip)||thisPort!=port){
                    initClient(ip, port);
                    host=ip;
                    thisPort=port;
                    ifNeedReconnect=false;
                }

                //封装
                RpcRequest request = new RpcRequest();
                String requestId = UUID.randomUUID().toString();

                String className = method.getDeclaringClass().getName();
                String methodName = method.getName();

                Class<?>[] parameterTypes = method.getParameterTypes();

                request.setRequestId(requestId);
                request.setClassName(className);
                request.setMethodName(methodName);
                request.setParameterTypes(parameterTypes);
                request.setParameters(args);



                // 设置参数
                userClientHandler.setPara(request);

                // 去服务端请求数据
                Object o =executor.submit(userClientHandler).get();

                if (o.equals("success")){
                    System.out.println("服务器"+ip+":"+port+"已响应");
                }else {

                    System.out.println(userClientHandler.getResult());
                    ifNeedReconnect=true;
                    /*if (!channelFuture.channel().isActive()) {//& !ifConnecting
                        System.out.println("尝试重连");
                        close();
                        initClient(ip,port);
//                      connect(ip, port, MAX_RETRY);
                        Thread.sleep(2000);
                    }*/



                }
                return o;
            }
        });


    }



    //2.初始化netty客户端
    public static  void initClient(String ip,int port) throws InterruptedException {
         userClientHandler = new UserClientHandler();

        group = new NioEventLoopGroup();

        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(userClientHandler);
//                      pipeline.addLast("ping",new IdleStateHandler(60,20,60*10, TimeUnit.SECONDS));

                    }
                });


//        bootstrap.connect(ip,port).sync();//sync使方法同步
        connect(ip,port,MAX_RETRY);
    }

    /**
     * 失败重连机制，参考Netty入门实战掘金小册
     *
     */
    public static void connect(String host, int port, int retry) throws InterruptedException {
//        ifConnecting=true;

//            channelFuture = bootstrap.connect(host,port).sync();
            channelFuture = bootstrap.connect(host, port).sync().addListener(future -> {
                if (future.isSuccess()) {
                    System.out.println("连接服务端成功");
    //                ifConnecting=false;
                } else if (retry == 0) {
                    System.out.println("重试次数已用完，放弃连接");
    //                ifConnecting=false;
                } else {
                    //第几次重连：
                    int order = (MAX_RETRY - retry) + 1;
                    //本次重连的间隔
                    int delay = 1 << order;
                    System.out.println(new Date()+"{} : 连接失败，第 "+order+" 次重连....");
                    bootstrap.config().group().schedule(() -> {
                        try {
                            connect(host, port, retry - 1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }, delay, TimeUnit.SECONDS);
                }
            });

        channel = channelFuture.channel();
    }


    public void close() {
        group.shutdownGracefully();
        channel.closeFuture().syncUninterruptibly();
    }


    public static ExecutorService getExecutor() {
        return executor;
    }

    public static void setExecutor(ExecutorService executor) {
        RpcConsumer.executor = executor;
    }

//    public static UserClientHandler getUserClientHandler() {
//        return userClientHandler;
//    }
//
//    public static void setUserClientHandler(UserClientHandler userClientHandler) {
//        RpcConsumer.userClientHandler = userClientHandler;
//    }

    public static Bootstrap getBootstrap() {
        return bootstrap;
    }

    public static void setBootstrap(Bootstrap bootstrap) {
        RpcConsumer.bootstrap = bootstrap;
    }

    public static ChannelFuture getChannelFuture() {
        return channelFuture;
    }

    public static void setChannelFuture(ChannelFuture channelFuture) {
        RpcConsumer.channelFuture = channelFuture;
    }

    public static EventLoopGroup getGroup() {
        return group;
    }

    public static void setGroup(EventLoopGroup group) {
        RpcConsumer.group = group;
    }

    public static int getMaxRetry() {
        return MAX_RETRY;
    }

    public static Channel getChannel() {
        return channel;
    }

    public static void setChannel(Channel channel) {
        RpcConsumer.channel = channel;
    }

    public static Boolean getIfConnecting() {
        return ifConnecting;
    }

    public static void setIfConnecting(Boolean ifConnecting) {
        RpcConsumer.ifConnecting = ifConnecting;
    }
}
